package com.zy.datareceiver.binsess.exec.conf;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;

@EnableAsync
@Configuration
public class BaseExecutorConfig {

    private static final Logger log = LoggerFactory.getLogger(BaseExecutorConfig.class);

    @Value("${core.pool.size}")
    private Integer corePoolSize = 20;
    @Value("${max.pool.size}")
    private Integer maxPoolSize = 20;
    @Value("${queue.capacity}")
    private Integer queueCapacity = 200;
    @Value("${keep.alive.seconds}")
    private Integer KeepAliveSeconds = 60;

    @Bean("taskExecutor")
    public Executor taskExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(KeepAliveSeconds);
        executor.setThreadNamePrefix("taskExecutor-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setThreadFactory(new ThreadFactory() {
            //添加线程守护
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                if (thread.isDaemon()){
                    thread.setDaemon(false);
                }
                if (Thread.NORM_PRIORITY == thread.getPriority()){
                    thread.setPriority(Thread.NORM_PRIORITY);
                }
                //线程出现异常之后打印异常信息
                thread.setUncaughtExceptionHandler((Thread t,Throwable ex) ->{
                    try {
                        log.error(t.getName()+ t.getState()+ ": " + ex.getMessage());
                        Thread.sleep(1000);
                        executor.execute(r,1000);
                    } catch (InterruptedException e) {
                        executor.execute(r,1000);
                    }
                });
                return thread;
            }
        });

        return executor;
    }
}
